<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/html">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="/js/jquery-3.0.0.min.js"></script>
    <title>My WebSocket</title>
</head>
<style type="text/css">
    .div1 {
        position: absolute;
        top: 10%;
        left: 20%;
        width: 15%;
        height: 600px;
        border: 2px solid black;
    }

    .div2 {
        position: absolute;
        top: 10%;
        left: 50%;
        width: 25%;
        height: 600px;
        border: 2px solid black;
    }

    .div3 {
        position: absolute;
        top: 75%;
        left: 20%;
        width: 55%;
        height: 100px;
        border: 2px solid black;
    }

    .Absolute-Center {
        width: 50%;
        height: 50%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0; /*css溢出法*/
        margin: auto;
    }
</style>
<body>
<div class="div1">
    <center>在線人數列表</center>
    <div id="onLine"></div>
</div>
<div class="div2" id="message">
    <center>聊天記錄</center>
</div>
<div class="div3">
    <table class="Absolute-Center">
        <tr>
            <td>
                <select id="optionNames">
                    <option value="all">all</option>
                </select>
            </td>
            <td>
                <input id="content" type="text"/>
            </td>
            <td>
                <button onclick="send()">發送</button>
            </td>
            <td>
                <button onclick="closeWebSocket()">下線</button>
            </td>
        </tr>
    </table>
</div>
</body>
<script type="text/javascript">
    // 自動生成用戶名
    var username = randomString();
    var websocket = null;
    var date = new Date().toLocaleString();
    //判斷當前瀏覽器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/chat/" + username);
    }
    else {
        alert('Not support websocket')
    }

    //連接發生錯誤的回調方法
    websocket.onerror = function () {
        setMessageInnerHTML(date + ":" + username + "連接出錯");
    };

    //連接成功建立的回調方法
    websocket.onopen = function (event) {
        var messageBody = username + "----->連接成功";
        setMessageInnerHTML(messageBody);
    }

    //接收到消息的回調方法
    websocket.onmessage = function (event) {
        var data = event.data;
        var result1 = data.indexOf("加入聊天室，當前在線人數爲");
        var result2 = data.indexOf("下線,當前在線人數爲");
        if (result1 != -1) {
            //用戶接受新用戶加入聊天室信息
            var position = data.indexOf("_");
            var onlineNames = data.slice(position + 1);
            var messageBody = data.substring(0, position);
            setMessageInnerHTML(messageBody);
            var array = onlineNames.split(",");
            var optionNames = document.getElementById("optionNames");
            optionNames.options.length = 0;
            optionNames.options.add(new Option("all", "all"));
            for (var i = 0; i < array.length; i++) {
                optionNames.options.add(new Option(array[i], array[i]));
            }
            getOnLineInnerHTML();
        } else if (result2 != -1) {
            //用戶接受其他用戶下線通知
            var position = data.indexOf("_");
            var onlineNames = data.slice(position + 1);
            var messageBody = data.substring(0, position);
            setMessageInnerHTML(messageBody);
            var array = onlineNames.split(",");
            var optionNames = document.getElementById("optionNames");
            optionNames.options.length = 0;
            optionNames.options.add(new Option("all", "all"));
            for (var i = 0; i < array.length; i++) {
                optionNames.options.add(new Option(array[i], array[i]));
            }
            getOnLineInnerHTML();
        } else {
            setMessageInnerHTML(data);
        }
    }

    //連接關閉的回調方法
    websocket.onclose = function () {
        setMessageInnerHTML(date + ":" + username + "----->下線");
    }

    //監聽窗口關閉事件，當窗口關閉時，主動去關閉websocket連接，防止連接還沒斷開就關閉窗口，server端會拋異常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    //將消息顯示在網頁上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //將在線人數顯示在網頁上
    function getOnLineInnerHTML() {
        var optionNames = document.getElementById("optionNames");
        var onLineNames = "";
        for (var i = 1; i < optionNames.options.length; i++) {
            var onLineName = optionNames.options[i].value + '<br/>';
            onLineNames += onLineName;
        }
        document.getElementById('onLine').innerHTML = onLineNames;
    }

    //關閉連接
    function closeWebSocket() {
        websocket.close();
    }

    //發送消息
    function send() {
        var toName = $("#optionNames").find("option:selected").text();
        var content = $("#content").val();
        var messageBody = {
            "content": content,
            "toName": toName
        };
        websocket.send(JSON.stringify(messageBody));
    }

    function randomString() {
        var len = 3;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        /****默認去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var string = '';
        for (i = 0; i < len; i++) {
            string += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return string;
    }
</script>

</html>